package service

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"shangyuapi/data_source"
	"shangyuapi/models"
	"shangyuapi/redis_lib"
	"time"
)

func Citylist() []models.City {
	var citys []models.City
	ctx := context.Background()
	cityslist, _ := redis_lib.Client.Get(ctx, "shangyucityslist").Result()

	if cityslist == "" || len(cityslist) == 0 || cityslist == "null" {
		data_source.Db.Debug().Where("type < 4").Find(&citys)

		byte_data, _ := json.Marshal(citys)
		str := string(byte_data)
		redis_lib.Client.Set(ctx, "shangyucityslist", str, -1)
	} else {
		json.Unmarshal([]byte(cityslist), &citys)
	}
	return citys
}
func Citys() []models.City {
	var citys []models.City
	ctx := context.Background()
	cityslist, _ := redis_lib.Client.Get(ctx, "shangyucitys").Result()
	if cityslist == "" || len(cityslist) == 0 || cityslist == "null" {
		data_source.Db.Where("type = 2").Find(&citys)
		byte_data, _ := json.Marshal(citys)
		str := string(byte_data)
		redis_lib.Client.Set(ctx, "shangyucitys", str, -1)
	} else {
		json.Unmarshal([]byte(cityslist), &citys)
	}
	return citys
}

func Miyao() (miyao string) {
	var shangyumiyao string
	ctx := context.Background()
	shangyumiyaoinfo, _ := redis_lib.Client.Get(ctx, "shanyumiyao").Result()
	shangyumiyao = shangyumiyaoinfo
	if shangyumiyao == "" || len(shangyumiyao) == 0 || shangyumiyao == "null" {
		postData := []byte(``)
		// 创建请求
		req, err := http.NewRequest("POST", "https://zhongyi.jiayixunfang.cn/admin/miyao", bytes.NewBuffer(postData))
		if err != nil {
			panic(err)
		}
		// 设置Content-Type
		req.Header.Set("Content-Type", "application/json")

		// 发送请求
		client := &http.Client{}
		resp, err := client.Do(req)
		if err != nil {
			panic(err)
		}
		defer resp.Body.Close()
		body1, err := ioutil.ReadAll(resp.Body)
		//fmt.Println(string(body1))
		if err != nil {
			fmt.Println(err)
		}
		r := T{}
		err = json.Unmarshal(body1, &r)

		if err != nil {
			fmt.Println(err)
		}
		redis_lib.Client.Set(ctx, "shanyumiyao", r.Data, 86400*time.Second)
		return r.Data

	}
	return shangyumiyao

}

type T struct {
	Code    int    `json:"code"`
	Data    string `json:"data"`
	Error   int    `json:"error"`
	Msg     string `json:"msg"`
	Success int    `json:"success"`
}
